//
//  FindDetailsViewController.m
//  SugarPile
//
//  Created by Charlie. on 16/1/26.
//  Copyright © 2016年 www.lanou39.蓝鸥科技. All rights reserved.
//

#import "FindDetailsViewController.h"
#import "LCPrefixHeader.pch"
#import "HotModel.h"
#import "HotCollectionViewCell.h"
#import "HotDetailsViewController.h"
#import "FindDetailsModel.h"

#import "DataBaseManager.h"
#import "Movie.h"
@interface FindDetailsViewController ()<LCLayoutItemHeightDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UICollectionView *collectionView; /**<瀑布流*/
@property (nonatomic, retain) NSMutableArray *dataArr; /**<数据数组*/
@property (nonatomic, copy) NSString *strURL; /**<记录拼接后的网址*/
@property (nonatomic, assign) NSInteger i; /**<记录网页加载数*/
@property (nonatomic, assign) BOOL isLogin; /**<记录状态*/
@property (nonatomic, retain) UIView *screenView; /**<筛选模块*/
@property (nonatomic, retain) UITableView *screenTableView; /**<筛选Table*/
@property (nonatomic, retain) NSArray *screenArr; /**<筛选数据*/
@property (nonatomic, assign) BOOL screenLogin; /**<记录筛选数据处理状态*/
@property (nonatomic, copy) NSString *screenStr; /**<记录传输的数据*/

@property (nonatomic, retain) NSMutableArray *imagedataArr; /**<记录上方图片的iamge*/
@property (nonatomic, copy) NSString *imageStr; /**<接受字符串*/


@end

@implementation FindDetailsViewController
-(void)dealloc
{
    [_collectionView release];
    [_dataArr release];
    [_strURL release];
    [_screenView release];
    [_screenTableView release];
    [_screenArr release];
    [_screenStr release];
    [_imagedataArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];//导航条返回键带的首页 让他消失
        // collcetion
    // 判断是否有筛选价格
    if ([_str isEqualToString:@"5459e65e586df57518d70ff6"] || [_str isEqualToString:@"56022756f7ca8779ec7a9ca2"] || [_str isEqualToString:@"5567030a586df51f2bfa3489"]) {
        self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"筛选价格" style:UIBarButtonItemStylePlain target:self action:@selector(right)] autorelease];
                 self.isLogin = YES;
    }
    
    
    [self createCollcetion];
    
    
    
    // 筛选View TableView
    [self createView];
    // 初始化
    self.screenLogin = YES;
    // 数据处理
    [self dataHandle];

    
    // 解析数据
    [self imagedataArrHandle];
   
//     创建手势对象
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
////    // 把手势添加给视图
//    [self.view addGestureRecognizer:tap];
//    [tap release];
    // 下拉刷新
    [self refresh];
    
    // 上拉加载
    [self loading];

    
    
}


// 筛选判断
- (void)right
{
    _isLogin = !_isLogin;
    if (_isLogin == YES) {
        _screenView.hidden = YES;
    }else{
        _screenView.hidden = NO;
    }
}

#pragma mark - 筛选数组
- (void)createView
{
    // 创建一个选项数组
    self.screenArr = @[@"筛选价格",@"不限价格", @"¥0-100", @"¥100-200", @"¥200-500", @"多于¥500"];
    
    
    self.screenView = [[BaseView alloc] initWithFrame:CGRectMake(0, 0, (WIDTH - 39) * W, (WIDTH - 40 - 69) * H)];
    _screenView.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    [self.view addSubview:_screenView];
    _screenView.backgroundColor = [UIColor lightGrayColor];
    _screenView.hidden = YES;
    [_screenView release];
    
    
    // 创建tableView
    self.screenTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, (WIDTH - 40) * W, (WIDTH - 40 - 70) * H) style:UITableViewStylePlain];
    
    // 协议方法
    _screenTableView.delegate = self;
    _screenTableView.dataSource = self;
    // 边缘弹动
    _screenTableView.bounces = NO;

    _screenTableView.backgroundColor = [UIColor floralWhite];
    [_screenView addSubview:_screenTableView];
    [_screenTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"screenCell"];
    [self.screenView release];
    
}
- (void)createCollcetion
{

    // 自定义Layout 布局
    LClayout *layout = [[LClayout alloc] init];
    layout.columcounts = 2;
    layout.columSpace = 15;
    layout.rowSpace = 15;
    layout.edgeInsets = UIEdgeInsetsMake(15, 15, 15, 15);
    // 代理人
    layout.delegate = self;

    // coleation 属性
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:layout];
    // 协议
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    // 设置上边距 用来放置 伦布图
    _collectionView.contentInset = UIEdgeInsetsMake(100 * H, 0, 0, 0);
    // 添加父视图
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = [UIColor floralWhite];
    // 重用池
    [_collectionView registerClass:[HotCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_collectionView release];
    [layout release];

}
// 图片
- (void)createImage
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, -149 * H)];
    [_collectionView addSubview:view];
//    view.backgroundColor = [UIColor waterPink];
    
    //  创建需要的毛玻璃特效类型
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
    //  毛玻璃view 视图
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
   
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:view.bounds];
    [view addSubview:imageView];
//    imageView.backgroundColor = [UIColor salmonColor];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [imageView sd_setImageWithURL:[NSURL URLWithString:[_imageStr stringByReplacingOccurrencesOfString:@"_webp" withString:@""]]];
    //添加到要有毛玻璃特效的控件中
    effectView.alpha = 0.7;
    effectView.frame = imageView.bounds;
    [imageView addSubview:effectView];
    
    for (NSInteger i = 0; i < _imagedataArr.count; i++) {
        FindDetailsModel *m = _imagedataArr[i];
        NSLog(@"%@", m.name);
        
        UILabel *label = [[UILabel alloc] init];
        label.text = [NSString stringWithFormat:@"# %@", m.name];
        label.font = [UIFont systemFontOfSize:11];
        label.textAlignment = NSTextAlignmentCenter;
        label.frame = CGRectMake(W * (50 + 55 * i), -85 * H, 55, 30);

        if (i > 4) {
            label.frame = CGRectMake(W * (50 + 55 * (i - 5)), -55 * H, 55, 30);
        }
        if (i > 9) {
            label.frame = CGRectMake(W * (50 + 55 * (i - 10)), -25 * H, 55, 30);
        }
                [view addSubview:label];
        [label release];
    }
    
}
// 图片数据处理
- (void)imagedataArrHandle
{
    NSString *str = @"http://203.80.144.212/napi/category/detail/?category_id=56022756f7ca8779ec7a9ca2&platform_version=4.4.4&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522175480%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=68&platform_name=Android&locale=zh&app_code=nayutas";
    NSString *url = [str stringByReplacingOccurrencesOfString:@"id=56022756f7ca8779ec7a9ca2" withString:[NSString stringWithFormat:@"id=%@", _str]];
    [LCAFNetWorking GETWithURL:url completion:^(id result) {
        self.imagedataArr = [FindDetailsModel modelHanderWithArray:   result[@"data"][@"sub_cates"]];
        
        self.navigationItem.title = result[@"data"][@"name"];
        
        [_collectionView reloadData];
        
    }];
}
- (void)dataHandle
{
    if (_screenLogin == NO) {
        // 获取需要拼接的数据
        NSString *str = @"http://www.duitang.com/napi/blog/list/by_category/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&filter_params=%7B%22price%22%3A%22%5B*+TO+100%5D%22%7D&path=&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522847630%2522%257D&screen_width=720&screen_height=1280&app_version=68&start=0&platform_name=Android&locale=zh&app_code=nayutas&cate_key=5459e65e586df57518d70ff6";
        NSString *url = [str stringByReplacingOccurrencesOfString:@"key=5459e65e586df57518d70ff6" withString:[NSString stringWithFormat:@"key=%@", _str]];
        NSString *strURL = [url stringByReplacingOccurrencesOfString:@"*+TO+100" withString:_screenStr];
        
        // 记录拼接后的网址
        self.strURL = strURL;

        
    }else{
    
    // 获取需要拼接的数据
    NSString *str = @"http://203.80.144.213/napi/blog/list/by_category/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&path=&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522441199%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=68&start=0&platform_name=Android&locale=zh&app_code=nayutas&cate_key=5459e65e586df57518d70ff6";
    NSString *url = [str stringByReplacingOccurrencesOfString:@"key=5459e65e586df57518d70ff6" withString:[NSString stringWithFormat:@"key=%@", _str]];
    
    // 记录拼接后的网址
    self.strURL = url;
    }
    
    [LCAFNetWorking GETWithURL:self.strURL completion:^(id result) {
        
        self.dataArr = [HotModel modelHanderWithArray:result[@"data"][@"object_list"]];
        
        // 记录当前头图片网址
       self.imageStr = result[@"data"][@"object_list"][0][@"photo"][@"path"];
        // 创建头Image
        [self createImage];
        
        [_collectionView reloadData];
    }];
    
    
}
#pragma mark - table 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"screenCell" forIndexPath:indexPath];
    cell.textLabel.text = _screenArr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _screenLogin = NO;
    if (indexPath.row == 1) {
        _screenLogin = YES;
        _screenView.hidden = YES;
        _isLogin = YES;
        // 刷新之前清除数组内容 让自定义layout内部数组清除
        [self.dataArr removeAllObjects];
        // 刷新当前页面
        [self.collectionView.mj_header beginRefreshing];
        // 执行方法
        [self dataHandle];
    }else if (indexPath.row == 2){
        _screenStr = @"*+TO+100";
        _screenView.hidden = YES;
        _isLogin = YES;
        // 刷新之前清除数组内容 让自定义layout内部数组清除
        [self.dataArr removeAllObjects];
        // 刷新当前页面
        [self.collectionView.mj_header beginRefreshing];
        // 执行方法
        [self dataHandle];
    }else if (indexPath.row == 3){
        _screenStr = @"100+TO+200";
        _screenView.hidden = YES;
        _isLogin = YES;
        // 刷新之前清除数组内容 让自定义layout内部数组清除
        [self.dataArr removeAllObjects];
        // 刷新当前页面
        [self.collectionView.mj_header beginRefreshing];
        // 执行方法
        [self dataHandle];
    }else if (indexPath.row == 4){
        _screenStr = @"200+TO+500";
        _screenView.hidden = YES;
        _isLogin = YES;
        // 刷新之前清除数组内容 让自定义layout内部数组清除
        [self.dataArr removeAllObjects];
        // 刷新当前页面
        [self.collectionView.mj_header beginRefreshing];
        // 执行方法
        [self dataHandle];
    }else if (indexPath.row == 5){
        _screenStr = @"500+TO+*";
        _screenView.hidden = YES;
        _isLogin = YES;
        // 刷新之前清除数组内容 让自定义layout内部数组清除
        [self.dataArr removeAllObjects];
        // 刷新当前页面
        [self.collectionView.mj_header beginRefreshing];
        // 执行方法
        [self dataHandle];
    }
}
#pragma mark - collection协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return _dataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    // 定义当前cell的Model
    if (_dataArr.count != 0) {

        HotModel *m = _dataArr[indexPath.item];
        // 传入当前cell
        cell.model = m;
       
    }

    
    
    return cell;
}
// 自定义layout 布局方法
-(CGFloat)layout:(LClayout *)layout heightForItemAtindexPath:(NSIndexPath *)indexPath width:(CGFloat)width
{
    // tw/wh = iw/ih
    
    HotModel *m = _dataArr[indexPath.item];
    CGFloat h = width * m.height.doubleValue / m.width.doubleValue;
    
    //文本高度
    CGFloat textHeight = [HotCollectionViewCell heightWithText:m.msg Size:9];
    //判断文本框 高度是否 超过 15.51 * 6 的 高度(6行的高度)
    if (textHeight >= 15.51 * 6) {
        //设置最大文本框行数 为 6行;
        textHeight = 15.51 * 6;
    }
    // 每个cell的高度 由 图片高度 和 文本高度  + 其他控件高度(80)
    return h + textHeight + 80;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HotDetailsViewController *hotDetailsVC = [[[HotDetailsViewController alloc] init] autorelease];
    hotDetailsVC.hidesBottomBarWhenPushed = YES;
    HotModel *m = _dataArr[indexPath.item];
    //    NSLog(@"%ld", _index.item );
    hotDetailsVC.detailsId = m.ID;
    [self.navigationController pushViewController:hotDetailsVC animated:YES];

}
#pragma mark - 上拉加载
- (void)loading
{
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _i += 24;
        // 延迟两秒
        //       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 判断是否为 筛选内容 如果为筛选数据则
        if (_screenLogin == NO) {
            // 获取需要拼接的数据
            // 放入网址
            NSString *str = @"http://www.duitang.com/napi/blog/list/by_category/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&filter_params=%7B%22price%22%3A%22%5B*+TO+100%5D%22%7D&path=&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522847630%2522%257D&screen_width=720&screen_height=1280&app_version=68&start=0&platform_name=Android&locale=zh&app_code=nayutas&cate_key=5459e65e586df57518d70ff6";
            // 根据点击cell传入id 进行拼接
            NSString *url = [str stringByReplacingOccurrencesOfString:@"key=5459e65e586df57518d70ff6" withString:[NSString stringWithFormat:@"key=%@", _str]];
            // 根据点击筛选Cell 进行判断 拼接
            NSString *string = [url stringByReplacingOccurrencesOfString:@"*+TO+100" withString:_screenStr];
            // 根据加载 拼接变量 i
            NSString *strURL = [string stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%ld", _i]];
            // 记录拼接后的网址
            self.strURL = strURL;
            
            
        }else{
            
        // 加载的原网址
        NSString *str = @"http://203.80.144.213/napi/blog/list/by_category/?include_fields=sender%2Calbum%2Cicon_url%2Creply_count%2Clike_count&platform_version=4.4.4&path=&device_platform=HM%2B2A&__dtac=%257B%2522_r%2522%253A%2520%2522441199%2522%257D&screen_width=720&screen_height=1280&__domain=www.duitang.com&app_version=68&start=0&platform_name=Android&locale=zh&app_code=nayutas&cate_key=5459e65e586df57518d70ff6";
            // 根据点击cell进行拼接
        NSString *url = [str stringByReplacingOccurrencesOfString:@"key=5459e65e586df57518d70ff6" withString:[NSString stringWithFormat:@"key=%@", _str]];
            // 根据加载次数 拼接 i值
        NSString *strURL = [url stringByReplacingOccurrencesOfString:@"start=0" withString:[NSString stringWithFormat:@"start=%ld", _i]];
            
            self.strURL = strURL;
        }
        [LCAFNetWorking GETWithURL:self.strURL completion:^(id result) {
            
            NSArray *temp = result[@"data"][@"object_list"];
            NSArray *aTemp = [HotModel modelHanderWithArray:temp];
            // 遍历新得到的数组 将新数组添加到源数组中
            for (HotModel *m in aTemp) {
                [self.dataArr addObject:m];
            }
            NSLog(@"%ld", _i);
            
            // 刷新
            [_collectionView reloadData];
        }];
        //
        [_collectionView.mj_footer endRefreshing];
        
        //       });
        
    }];
    _collectionView.mj_footer = footer;
}
#pragma mark - 下拉刷新
- (void)refresh
{
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //延迟2秒
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
        //                       dispatch_get_main_queue(),^{
        
        // 刷新
        _i = 24;
        // 清空 源数组
        [self.dataArr removeAllObjects];
        // 重新获取解析数据
        [self dataHandle];
        //新版本是 MJ_header
        [self.collectionView.mj_header endRefreshing];
        //                       });
    }];
    self.collectionView.mj_header = header;
    //    header.stateLabel.font = [UIFont systemFontOfSize:12];
}

// 刷新方法
- (void)array:(NSMutableArray *)arr
{
//    // 当源数组清空时 让自定义layout内数据同步清空
    if (_dataArr.count == 0) {
        [arr removeAllObjects];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
// 创建手势
//- (void)tapAction:(UITapGestureRecognizer *)tap
//{
//    if (_isLogin == NO) {
//        _screenView.hidden = YES;
//        _isLogin = !_isLogin;
//    }
//}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 只要试图滚动 就一直触发该方法
    if (_isLogin == NO) {
        _screenView.hidden = YES;
        _isLogin = !_isLogin;
    }

}
#pragma mark - 设置导航栏
//视图将要出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    /** 设置导航栏不透明 **/
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"clear_nav"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
}

//视图将要消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"red"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}
#pragma mark - 文本宽度方法
+ (CGFloat)widthWithText:(NSString *)text Size:(CGFloat)fontSize
{
    //保存文本属性
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    //设置最大 尺寸
    //高度于label一致
    CGSize size = CGSizeMake(500, 10);
    //计算出 出一个 rect
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    //返回得到的宽度
    return rect.size.width;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
